// package com.study.crypto.basic.pdf;
//
// import com.itextpdf.kernel.pdf.PdfReader;
// import com.itextpdf.kernel.pdf.StampingProperties;
// import com.itextpdf.signatures.*;
// import com.study.crypto.basic.utils.CertUtils;
// import com.study.crypto.basic.utils.EssPdfUtil;
// import org.apache.commons.collections4.CollectionUtils;
// import org.bouncycastle.asn1.x509.Certificate;
// import org.bouncycastle.jce.provider.BouncyCastleProvider;
//
// import java.io.FileOutputStream;
// import java.io.IOException;
// import java.io.InputStream;
// import java.io.OutputStream;
// import java.security.GeneralSecurityException;
// import java.security.PrivateKey;
// import java.security.Security;
// import java.security.cert.X509Certificate;
// import java.util.Date;
// import java.util.List;
//
// /**
//  * @author Songjin
//  * @since 2021-09-21 20:08
//  */
// public class PdfDetachedPkcs7Container {
//
//     private PrivateKey        privateKey;
//     private List<Certificate> chain;
//     private InputStream       input;
//     private OutputStream      output;
//
//     public void signDetached() throws IOException, GeneralSecurityException {
//         BouncyCastleProvider provider = new BouncyCastleProvider();
//         Security.addProvider(provider);
//
//         PdfReader reader = new PdfReader(input);
//         PdfSigner signer = new PdfSigner(reader, output, new StampingProperties());
//
//         // Create the signature appearance
//         PdfSignatureAppearance appearance = signer.getSignatureAppearance();
//         appearance.setReason(reason);
//         appearance.setLocation(location);
//
//         // Set the rendering mode for this signature.
//         appearance.setRenderingMode(PdfSignatureAppearance.RenderingMode.GRAPHIC);
//         // Set the Image object to render when the rendering mode is set to RenderingMode.GRAPHIC
//         appearance.setSignatureGraphic(image);
//
//         // This name corresponds to the name of the field that already exists in the document.
//         signer.setFieldName(EssPdfUtil.genRandomUuid());
//
//         PrivateKeySignature pks    = new PrivateKeySignature(privateKey, digestAlgorithm, provider);
//         IExternalDigest     digest = new BouncyCastleDigest();
//
//         // Sign the document using the detached mode, CMS or CAdES equivalent.
//         X509Certificate[] realchain;
//         if (CollectionUtils.isNotEmpty(chain)) {
//             realchain = new X509Certificate[chain.size()];
//             for (int i = 0; i < chain.size(); i++) {
//                 Certificate cert = chain.get(i);
//                 X509Certificate certificate = CertUtils.rebuildX509Certificate(cert.getEncoded());
//                 realchain[i] = certificate;
//             }
//         } else {
//             realchain = new X509Certificate[0];
//         }
//
//         signer.signDetached(digest, pks, realchain, null, null, null, 0, PdfSigner.CryptoStandard.CMS);
//     }
// }
